package com.zhuwhao.sample.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.zhuwhao.sample.R;

import java.util.List;

/**
 * Created by Juno on 2016/12/22 0022.
 * DropDownMenu
 */
public class DropDownMenu extends LinearLayout {

    //顶部TabView
    private LinearLayout tabViews;
    //弹出菜单View
    private FrameLayout popupViews;
    //遮罩View
    private View maskView;
    //选中的tab位置，-1表示未选中
    private int currentTabPosition = -1;

    //遮罩颜色
    private int maskColor;
    //popup最大高度
    private int popupMaxHeight;
    //tab背景色
    private int tabBackgroundColor;
    //tab分割线颜色
    private int tabDividerColor;
    //tab分割线上下margin
    private int tabDividerMargin;
    //tab分割线宽度
    private int tabDividerWidth;
    //tab高度
    private int tabHeight;
    //tabIcon宽高
    private int tabIconHeight;
    //tabIcon宽度
    private int tabIconWidth;
    //tab选中图标
    private int tabSelectedIcon;
    //tab文本paddingRight
    private int tabTextPaddingRight;
    //tab选中颜色
    private int tabTextSelectedColor;
    //tab字体大小
    private int tabTextSize;
    //tab未选中颜色
    private int tabTextUnselectedColor;
    //tab未选中图标
    private int tabUnselectedIcon;
    //tab下划线颜色
    private int underlineColor;
    //下划线高度
    private int underlineHeight;

    public DropDownMenu(Context context) {
        this(context, null);
    }

    public DropDownMenu(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DropDownMenu(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        setOrientation(VERTICAL);

        //自定义属性
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DropDownMenu, defStyleAttr, 0);
        maskColor = a.getColor(R.styleable.DropDownMenu_ddMaskColor, Color.parseColor("#50000000"));
        popupMaxHeight = a.getDimensionPixelSize(R.styleable.DropDownMenu_ddPopupMaxHeight, dp2px(360));
        tabBackgroundColor = a.getColor(R.styleable.DropDownMenu_ddTabBackgroundColor, Color.parseColor("#FFFFFF"));
        tabDividerColor = a.getColor(R.styleable.DropDownMenu_ddTabDividerColor, Color.parseColor("#D3D3D3"));
        tabDividerMargin = a.getDimensionPixelSize(R.styleable.DropDownMenu_ddTabDividerMargin, dp2px(8));
        tabDividerWidth = a.getDimensionPixelSize(R.styleable.DropDownMenu_ddTabDividerWidth, dp2px(1));
        tabHeight = a.getDimensionPixelSize(R.styleable.DropDownMenu_ddTabHeight, dp2px(40));
        tabIconHeight = a.getDimensionPixelSize(R.styleable.DropDownMenu_ddTabIconHeight, dp2px(10));
        tabIconWidth = a.getDimensionPixelSize(R.styleable.DropDownMenu_ddTabIconWidth, dp2px(10));
        tabSelectedIcon = a.getResourceId(R.styleable.DropDownMenu_ddTabSelectedIcon, R.drawable.ic_arrow_drop_up);
        tabTextPaddingRight = a.getDimensionPixelSize(R.styleable.DropDownMenu_ddTabTextPaddingRight, dp2px(2));
        tabTextSelectedColor = a.getColor(R.styleable.DropDownMenu_ddTabTextSelectedColor, Color.parseColor("#3F51B5"));
        tabTextSize = a.getDimensionPixelSize(R.styleable.DropDownMenu_ddTabTextSize, sp2px(12));
        tabTextUnselectedColor = a.getColor(R.styleable.DropDownMenu_ddTabTextUnselectedColor, Color.parseColor("#212121"));
        tabUnselectedIcon = a.getResourceId(R.styleable.DropDownMenu_ddTabUnselectedIcon, R.drawable.ic_arrow_drop_down);
        underlineColor = a.getColor(R.styleable.DropDownMenu_ddUnderlineColor, Color.parseColor("#D3D3D3"));
        underlineHeight = a.getDimensionPixelSize(R.styleable.DropDownMenu_ddUnderlineHeight, dp2px(1));
        a.recycle();
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        initView(getChildAt(0));
    }

    /**
     * 初始化所有控件
     *
     * @param contentView 内容视图
     */
    private void initView(View contentView) {
        removeAllViews();

        //初始化tabViews
        tabViews = new LinearLayout(getContext());
        tabViews.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, tabHeight));
        tabViews.setOrientation(HORIZONTAL);
        tabViews.setBackgroundColor(tabBackgroundColor);
        addView(tabViews, 0);

        //初始化underlineView
        View underlineView = new View(getContext());
        underlineView.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, underlineHeight));
        underlineView.setBackgroundColor(underlineColor);
        addView(underlineView, 1);

        //初始化containerView，底部容器，包含contentView，maskView，popupViews
        FrameLayout containerView = new FrameLayout(getContext());
        containerView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
        containerView.addView(contentView, 0);

        //初始化maskView
        maskView = new View(getContext());
        maskView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
        maskView.setBackgroundColor(maskColor);
        maskView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                close();
            }
        });
        maskView.setVisibility(GONE);
        containerView.addView(maskView, 1);

        //初始化popupViews
        popupViews = new FrameLayout(getContext());
        popupViews.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, popupMaxHeight));
        popupViews.setVisibility(GONE);
        containerView.addView(popupViews, 2);
        addView(containerView, 2);
    }

    /**
     * 设置DropDownMenu的Tab和Popup
     *
     * @param tabTexts tabTexts
     * @param views    views
     */
    public void setDropDownMenu(@NonNull List<String> tabTexts, @NonNull List<View> views) {
        if (tabTexts.size() != views.size()) {
            throw new IllegalArgumentException("params not match, tabTexts.size() should be equal views.size()");
        }

        for (int i = 0; i < tabTexts.size(); i++) {
            addTab(tabTexts, i);
        }

        for (int i = 0; i < views.size(); i++) {
            views.get(i).setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            popupViews.addView(views.get(i), i);
        }
    }

    /**
     * 添加Tab
     *
     * @param tabTexts tabTexts
     * @param i        i
     */
    private void addTab(@NonNull List<String> tabTexts, int i) {
        final LinearLayout tabView = new LinearLayout(getContext());
        tabView.setLayoutParams(new LayoutParams(0, LayoutParams.MATCH_PARENT, 1.0f));
        tabView.setOrientation(HORIZONTAL);
        tabView.setGravity(Gravity.CENTER);
        tabView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                switchPopup(tabView);
            }
        });
        tabViews.addView(tabView);

        final TextView tabText = new TextView(getContext());
        tabText.setSingleLine();
        tabText.setEllipsize(TextUtils.TruncateAt.END);
        tabText.setGravity(Gravity.CENTER);
        tabText.setTextSize(TypedValue.COMPLEX_UNIT_PX, tabTextSize);
        tabText.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        tabText.setTextColor(tabTextUnselectedColor);
        tabText.setText(tabTexts.get(i));
        tabText.setPadding(0, 0, tabTextPaddingRight, 0);
        tabView.addView(tabText, 0);

        ImageView tabIcon = new ImageView(getContext());
        tabIcon.setLayoutParams(new ViewGroup.LayoutParams(tabIconWidth, tabIconHeight));
        tabIcon.setBackgroundResource(tabUnselectedIcon);
        tabView.addView(tabIcon, 1);

        //添加分割线
        if (i < tabTexts.size() - 1) {
            View tabDivider = new View(getContext());
            LayoutParams params = new LayoutParams(tabDividerWidth, LayoutParams.MATCH_PARENT);
            params.topMargin = tabDividerMargin;
            params.bottomMargin = tabDividerMargin;
            tabDivider.setLayoutParams(params);
            tabDivider.setBackgroundColor(tabDividerColor);
            tabViews.addView(tabDivider);
        }
    }

    /**
     * 切换
     *
     * @param target target
     */
    private void switchPopup(View target) {
        for (int i = 0; i < tabViews.getChildCount(); i = i + 2) {
            if (target == tabViews.getChildAt(i)) {
                if (currentTabPosition == i) {
                    close();
                } else {
                    if (currentTabPosition == -1) {
                        popupViews.setVisibility(VISIBLE);
                        popupViews.setAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.dd_popup_in));
                        maskView.setVisibility(VISIBLE);
                        maskView.setAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.dd_mask_in));
                        popupViews.getChildAt(i / 2).setVisibility(VISIBLE);
                    } else {
                        popupViews.getChildAt(i / 2).setVisibility(VISIBLE);
                        hideSoftInput();
                    }
                    currentTabPosition = i;
                    ((TextView) ((LinearLayout) tabViews.getChildAt(i)).getChildAt(0)).setTextColor(tabTextSelectedColor);
                    ((LinearLayout) tabViews.getChildAt(i)).getChildAt(1).setBackgroundResource(tabSelectedIcon);
                }
            } else {
                ((TextView) ((LinearLayout) tabViews.getChildAt(i)).getChildAt(0)).setTextColor(tabTextUnselectedColor);
                ((LinearLayout) tabViews.getChildAt(i)).getChildAt(1).setBackgroundResource(tabUnselectedIcon);
                popupViews.getChildAt(i / 2).setVisibility(GONE);
            }
        }
    }

    /**
     * 关闭菜单
     */
    public void close() {
        if (currentTabPosition != -1) {
            ((TextView) ((LinearLayout) tabViews.getChildAt(currentTabPosition)).getChildAt(0)).setTextColor(tabTextUnselectedColor);
            ((LinearLayout) tabViews.getChildAt(currentTabPosition)).getChildAt(1).setBackgroundResource(tabUnselectedIcon);
            popupViews.setVisibility(GONE);
            popupViews.setAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.dd_popup_out));
            maskView.setVisibility(GONE);
            maskView.setAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.dd_mask_out));
            currentTabPosition = -1;
            hideSoftInput();
        }
    }

    /**
     * 设置tab文字
     *
     * @param text text
     */
    public void setTabText(String text) {
        if (currentTabPosition != -1) {
            ((TextView) ((LinearLayout) tabViews.getChildAt(currentTabPosition)).getChildAt(0)).setText(text);
        }
    }

    /**
     * 设置Tab是否能点击
     *
     * @param clickable clickable
     */
    public void setTabClickable(boolean clickable) {
        for (int i = 0; i < tabViews.getChildCount(); i = i + 2) {
            tabViews.getChildAt(i).setClickable(clickable);
        }
    }

    /**
     * DropDownMenu是否处于可见状态
     *
     * @return boolean
     */
    public boolean isVisible() {
        return currentTabPosition != -1;
    }

    /**
     * dp to px
     *
     * @param value dp
     * @return px
     */
    private int dp2px(float value) {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        return (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, dm) + 0.5f);
    }

    /**
     * sp to px
     *
     * @param value sp
     * @return px
     */
    private int sp2px(float value) {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        return (int) (TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, value, dm) + 0.5f);
    }

    /**
     * 隐藏软键盘
     */
    private void hideSoftInput() {
        InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(this.getWindowToken(), 0);
    }
}